
import re

import falcon

from WebBackend.middleware.virtualWorldGate_Chuche import login_require
from WebBackend.utils.executeCMD import execute_cmd_async


@falcon.before(login_require)
class ServiceStatusAPI:
    async def on_get(self, req, resp):
        target = req.params.get('name')
        # query_type = req.params.get('type')
        if target == 'vsftpd' or target == 'samba':
            text = await execute_cmd_async(f'systemctl status {target}', 'str')
            resp.media = process_results(text)
        else:
            raise falcon.HTTPNotFound()


def process_results(text: str) -> dict:
    result = {
        "service_status": None,
        "service_status_bool": None,
        "uptime": None,
        "autostart": None,
        "start_time": None,
    }
    # 1. 提取服务状态（Active: ...）
    if active_match := re.search(r"Active:\s+(.*?)\s+since", text):
        t: str = active_match.group(1).strip()
        result["service_status"] = t
        if 'inactive' in t.lower():
            result['service_status_bool'] = False
        else:
            result['service_status_bool'] = True

    # 2. 提取运行时长（... since ...; X week X days ago）
    if uptime_match := re.search(r"since.*?;\s+(.*?)\s+ago", text):
        result["uptime"] = uptime_match.group(1).strip()
    # 3. 检查是否开机自启（enabled/disabled）
    if autostart_match := re.search(r"Loaded:.*?;\s+(enabled|disabled)", text):
        result["autostart"] = autostart_match.group(1) == "enabled"
    # 4. 提取启动时间（since Tue 2025-05-27 12:32:58 HKT）
    time_match = re.search(r"since\s+\w{3}\s+(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\s+\w+)", text)
    if time_match:
        t = time_match.group(1).strip()
        t = t[2:]
        result["start_time"] = t

    print(result["start_time"])

    return result
